<template>
  <div>
    <div class="manage-title clearfix">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/panel/project/management' }">项目列表</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="upload-project">
        <el-upload
          style="width: 100%"
          class="upload-demo"
          action="http://47.96.125.181:8848/project/upload"
          :multiple="false"
          :show-file-list = "false"
          accept = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          :http-request="uploadFile">
          <el-button  size="small" :loading="loading" icon="el-icon-upload" type="success">批量新建</el-button>
        </el-upload>
      </div>
      <el-button type="primary" class="fr" size="small" @click="detailCheck">新建项目</el-button>

      <div class="serh">
        <el-input placeholder="请输入项目名称搜索" v-model="searchProjectInput" class="input-with-select">
          <el-button slot="append" icon="el-icon-search" @click="searchProjectList"></el-button>
        </el-input>
      </div>

    </div>
    <div class="form-block">
      <h4>筛选条件</h4>
      <el-button plain type="primary" class="fr" size="small" @click="dialogFilterVisible = true">编辑</el-button>
      <div class="filter-block">
        <span>项目类型：{{form.projTypeName}}</span>
        <span>联系人：{{form.contactMName}}</span>
        <span>负责人：{{form.responseMName}}</span>
        <span>立项日期：{{!form.projectDateCheck?form.projectDateValue: '不限'}}</span>
        <span>合同金额：{{!form.contractCheck? '¥'+form.paperAS+' - ¥'+form.paperAE: '不限'}}</span>
        <span>已到款金额：{{!form.receivedCheck? '¥'+form.receivedAS+' - ¥'+form.receivedAE: '不限'}}</span>
        <span>部门产值：{{!form.departmentOutputCheck? '¥'+form.departPS+' - ¥'+form.departPE: '不限'}}</span>
        <span>已结算产值：{{!form.balancedOutputCheck? '¥'+form.settledPS+' - ¥'+form.settledPE: '不限'}}</span>
        <span>项目状态：{{form.projectStateName}}</span>
        <span>合同是否已签署：{{form.signed}}</span>
      </div>
      <el-dialog
        title="编辑筛选条件"
        :visible.sync="dialogFilterVisible"
        :before-close = "handleFilterClose"
        @open = "handleOpen"
        width="50%"
        class="filter-eddit-dialog">
        <el-form  ref="form" v-model="form">
          <el-form-item label="项目类型：">
            <el-select v-model="form.projType" clearable placeholder="请选择" size="mini">
              <el-option
                v-for="item in form.projTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="联系人：">
            <el-select v-model="form.contactM" clearable placeholder="请选择" size="mini">
              <el-option
                v-for="item in form.contactMOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="负责人：">
            <el-select v-model="form.responseM" clearable placeholder="请选择" size="mini">
              <el-option
                v-for="item in form.responseMOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="立项日期：">
            <el-checkbox v-model="form.projectDateCheck">不限</el-checkbox>
            <el-date-picker
              v-model="form.projectDateValue"
              type="daterange"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              size="mini" v-if="!form.projectDateCheck">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="合同金额：">
            <el-checkbox v-model="form.contractCheck">不限</el-checkbox>
            <div class="input-group" v-if="!form.contractCheck">
              <el-input size="mini" v-model="form.paperAS"></el-input>
              -
              <el-input size="mini" v-model="form.paperAE"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="已到款金额：">
            <el-checkbox v-model="form.receivedCheck">不限</el-checkbox>
            <div class="input-group" v-if="!form.receivedCheck">
              <el-input size="mini" v-model="form.receivedAS"></el-input>
              -
              <el-input size="mini" v-model="form.receivedAE"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="部门产值：">
            <el-checkbox v-model="form.departmentOutputCheck">不限</el-checkbox>
            <div class="input-group" v-if="!form.departmentOutputCheck">
              <el-input size="mini" v-model="form.departPS"></el-input>
              -
              <el-input size="mini" v-model="form.departPE"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="已结算产值：">
            <el-checkbox v-model="form.balancedOutputCheck">不限</el-checkbox>
            <div class="input-group" v-if="!form.balancedOutputCheck">
              <el-input size="mini" v-model="form.settledPS"></el-input>
              -
              <el-input size="mini" v-model="form.settledPE"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="项目状态：">
            <el-select v-model="form.projectState" clearable placeholder="请选择" size="mini">
              <el-option
                v-for="item in form.projectStateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="已签署合同：">
            <el-radio-group v-model="form.signed">
              <el-radio label='不限'>不限</el-radio>
              <el-radio label='是'>是</el-radio>
              <el-radio label='否'>否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="restoreFilter">取 消</el-button>
          <el-button type="primary" @click="getProjects(currentPage,true)">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <el-table
      :data="tableData"
      border
      :stripe= 'true'
      class=""
      style="width:100%"
      @row-click="detailCheck">
      <el-table-column type="index" label="序号" align="center" width="50"></el-table-column>
      <el-table-column prop="ProjectTypeName" label="项目类型" width="80" align="center"></el-table-column>
      <el-table-column prop="ProjectNumber" label="项目编号" align="center"></el-table-column>
      <el-table-column prop="ProjectName" label="项目名称" align="center"></el-table-column>
      <el-table-column prop="OmName" label="联系人" width="80" align="center"></el-table-column>
      <el-table-column prop="PmName" label="负责人" width="80" align="center"></el-table-column>
      <el-table-column prop="CreatedDate" label="立项日期" align="center"></el-table-column>
      <el-table-column prop="ContractAmount" label="合同金额(￥)" align="center"></el-table-column>
      <el-table-column prop="ReceivedAmount" label="已到款(￥)" align="center"></el-table-column>
      <el-table-column prop="DepartmentOutput" label="部门产值(￥)" align="center"></el-table-column>
      <el-table-column prop="Proportion" label="占比(%)" align="center"></el-table-column>
      <el-table-column prop="BalancedOutput" label="已结算(￥)" align="center"></el-table-column>
      <el-table-column prop="StatusName" label="项目状态" align="center"></el-table-column>
    </el-table>
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-size="pageSize"
      layout="total, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        searchProjectInput:'',
        loading: false,
        droplist: {},
        token:'',
        total: 0,
        currentPage: 1,
        pageSize: 10,
        tableData: [],
        multipleSelection: [],
        filters: {
          name: ''
        },
        dialogFilterVisible:false,
        formHistroy:{},
        form:{
          projType:'不限',
          projTypeName:'不限',
          projTypeOptions:[
            {value:'不限',label:'-不限-'},
          ],
          contactM:'不限',
          contactMName:'不限',
          contactMOptions:[
            {value:'不限',label:'-不限-'},
          ],
          responseM:'不限',
          responseMName:'不限',
          responseMOptions:[
            {value:'不限',label:'-不限-'},
          ],
          projectState:'不限',
          projectStateName:'不限',
          projectStateOptions:[
            {value:'不限',label:'-不限-'},
            {value:0,label:'准备'},
            {value:1,label:'作业中'},
            {value:2,label:'作业完成'},
            {value:3,label:'归档'},
            {value:4,label:'结算'},
            {value:5,label:'结束'},

          ],
          projectDateCheck:true,
          projectDateValue:'',
          contractCheck:true,
          paperAS:'',
          paperAE:'',
          receivedCheck:true,
          receivedAS:'',
          receivedAE:'',
          departmentOutputCheck:true,
          departPS:'',
          departPE:'',
          balancedOutputCheck:true,
          settledPS:'',
          settledPE:'',
          signed:'不限'
        },

      }
    },
    created: function(){
      let user = JSON.parse(window.localStorage.getItem('access-user'))
      this.token = user.Token
      this.getDropList().then((flag) => {
        this.getProjects(this.currentPage,true)
      })
    },
    methods: {
      uploadFile (content) {
        this.loading = true
        let formData = new FormData()
        formData.append('Image', content.file)
        formData.append('Token', this.token)
        this.$http.post(this.domain + '/project/upload', formData)
          .then((response) => {
            this.getProjects(this.currentPage,false)
            this.$message.success(response.data.Msg)
            this.loading = false
          })
      },
      searchProjectList(){
        if (this.searchProjectInput === '') {
          this.getProjects(this.currentPage,true)
        } else {
          this.$http.post(this.domain + '/project/list/search',
            {
              token:this.token,
              name:this.searchProjectInput
            }
          ).then((response) => {
            if (response.data.Success) {
              this.dialogFilterVisible = false
              this.total = response.data.Total
              this.pageSize = this.total
              this.tableData = response.data.Projects
              for (var index in this.tableData) {
                this.tableData[index].CreatedDate = this.tableData[index].CreatedDate.split(' ')[0]
                for (var i in this.droplist.ProjectTypes) {
                  if (this.tableData[index].ContractAmount <= 0){
                    this.tableData[index].Proportion = "--"
                  } else {
                    this.tableData[index].Proportion = ((this.tableData[index].DepartmentOutput / this.tableData[index].ContractAmount) * 100).toFixed(2) + "%"
                  }
                  if (this.droplist.ProjectTypes[i].ProjectType === this.tableData[index].ProjectType){
                    this.tableData[index].ProjectTypeName = this.droplist.ProjectTypes[i].TypeName
                    break
                  }
                }
                for (var j in this.droplist.Oms) {
                  if (this.droplist.Oms[j].ID === this.tableData[index].OmId){
                    this.tableData[index].OmName = this.droplist.Oms[j].RealName
                    break
                  }
                }
                for (var k in this.droplist.Pms) {
                  if (this.droplist.Pms[k].ID === this.tableData[index].PmId){
                    this.tableData[index].PmName = this.droplist.Pms[k].RealName
                    break
                  }
                }
                for (var m in this.form.projectStateOptions) {
                  if (this.form.projectStateOptions[m].value === this.tableData[index].Status){
                    this.tableData[index].StatusName = this.form.projectStateOptions[m].label
                    break
                  }
                }
              }

              this.$message.success(response.data.Msg)
            } else {
              this.$message.error(response.data.Msg)
            }
          }).catch(function (response) {
            this.$message.error(response.data)
          })
        }
      },
      deepCopy(obj){
        if(typeof obj !== 'object'){
          return obj;
        }
        var newobj = {};
        for ( var attr in obj) {
          newobj[attr] = this.deepCopy(obj[attr]);
        }
        return newobj;
      },
      handleOpen () {
        this.formHistroy = this.deepCopy(this.form)
      },
      handleFilterClose (done) {
        this.form = this.deepCopy(this.formHistroy)
        done()
      },
      restoreFilter () {
        this.form = this.deepCopy(this.formHistroy)
        this.dialogFilterVisible = false
      },
      showFilter () {
        if (this.form.projType !== '不限') {
          for(var i in this.form.projTypeOptions) {
            if (this.form.projTypeOptions[i].value === this.form.projType){
              this.form.projTypeName = this.form.projTypeOptions[i].label
              break
            }
          }
        }
        if (this.form.contactM !== '不限') {
          for(var i in this.form.contactMOptions) {
            if (this.form.contactMOptions[i].value === this.form.contactM){
              this.form.contactMName = this.form.contactMOptions[i].label
              break
            }
          }
        }
        if (this.form.responseM !== '不限') {
          for(var i in this.form.responseMOptions) {
            if (this.form.responseMOptions[i].value === this.form.responseMM){
              this.form.responseMName = this.form.responseMOptions[i].label
              break
            }
          }
        }
        if (this.form.projectState !== '不限') {
          for(var i in this.form.projectStateOptions) {
            if (this.form.projectStateOptions[i].value === this.form.projectState){
              this.form.projectStateName = this.form.projectStateOptions[i].label
              break
            }
          }
        }
      },
      getProjects (page,flag) {
        this.showFilter()
        var args = {
          token: this.token,
          page:page,
        }
        if (this.form.projType !== '不限') {
          args.projecttype = this.form.projType
        }
        if (this.form.responseM !== '不限') {
          args.pmid = this.form.responseM
        }
        if (this.form.contactM !== '不限') {
          args.omid = this.form.contactM
        }
        if (this.form.projectState !== '') {
          args.status = this.form.projectState
        }
        if (this.form.signed !== '不限') {
          args.signed = this.form.signed === '是'
        }
        if (!this.form.projectDateCheck && this.form.projectDateValue.length === 2) {
          let begin = this.form.projectDateValue[0] + ' 00:00:00'
          let end = this.form.projectDateValue[1] + ' 00:00:00'
          args.createdate = begin +','+ end
        }
        if (!this.form.contractCheck) {
          if (isNaN(parseFloat(this.form.paperAS)) || isNaN(parseFloat(this.form.paperAE))) {
            this.$message.error('合同金额范围输入有误！')
            return
          }
          args.contractamount = parseFloat(this.form.paperAS)+','+ parseFloat(this.form.paperAE)
        }
        if (!this.form.receivedCheck) {
          if (isNaN(parseFloat(this.form.receivedAS)) || isNaN(parseFloat(this.form.receivedAE))) {
            this.$message.error('已到款金额范围输入有误！')
            return
          }
          args.receivedamount = parseFloat(this.form.receivedAS)+','+ parseFloat(this.form.receivedAE)
        }
        if (!this.form.departmentOutputCheck) {
          if (isNaN(parseFloat(this.form.departPS)) || isNaN(parseFloat(this.form.departPE))) {
            this.$message.error('部门产值范围输入有误！')
            return
          }
          args.departmentoutput = parseFloat(this.form.departPS)+','+ parseFloat(this.form.departPE)
        }
        if (!this.form.balancedOutputCheck) {
          if (isNaN(parseFloat(this.form.settledPS)) || isNaN(parseFloat(this.form.settledPE))) {
            this.$message.error('已结算产值范围输入有误！')
            return
          }
          args.balancedoutput = parseFloat(this.form.settledPS)+','+ parseFloat(this.form.settledPE)
        }
//        console.log(args)
        this.$http.post(this.domain + '/project/list',
          args
        ).then((response) => {
          if (response.data.Success) {
//            console.log(response.data)
            this.dialogFilterVisible = false
            this.total = response.data.Total
            this.pageSize = 10
            this.tableData = response.data.Projects
            for (var index in this.tableData) {
              this.tableData[index].CreatedDate = this.tableData[index].CreatedDate.split(' ')[0]
              for (var i in this.droplist.ProjectTypes) {
                if (this.tableData[index].ContractAmount <= 0){
                  this.tableData[index].Proportion = "--"
                } else {
                  this.tableData[index].Proportion = ((this.tableData[index].DepartmentOutput / this.tableData[index].ContractAmount) * 100).toFixed(2) + "%"
                }
                if (this.droplist.ProjectTypes[i].ProjectType === this.tableData[index].ProjectType){
                  this.tableData[index].ProjectTypeName = this.droplist.ProjectTypes[i].TypeName
                  break
                }
              }
              for (var j in this.droplist.Oms) {
                if (this.droplist.Oms[j].ID === this.tableData[index].OmId){
                  this.tableData[index].OmName = this.droplist.Oms[j].RealName
                  break
                }
              }
              for (var k in this.droplist.Pms) {
                if (this.droplist.Pms[k].ID === this.tableData[index].PmId){
                  this.tableData[index].PmName = this.droplist.Pms[k].RealName
                  break
                }
              }
              for (var m in this.form.projectStateOptions) {
                if (this.form.projectStateOptions[m].value === this.tableData[index].Status){
                  this.tableData[index].StatusName = this.form.projectStateOptions[m].label
                  break
                }
              }
            }
            if (flag) {
              this.$message.success(response.data.Msg)
            }
          } else {
            this.$message.error(response.data.Msg)
            this.dialogFilterVisible = false
          }
        }).catch(function (response) {
          this.$message.error(response.data)
          this.dialogFilterVisible = false
        })
      },
      getDropList () {
        return new Promise((resolve,reject) => {
          this.$http.post(this.domain + '/droplist', {
            token: this.token
          }).then((response) => {
            if (response.data.Success) {
              this.droplist = response.data
              for (var index in this.droplist.ProjectTypes) {
                var temp = {
                  value:this.droplist.ProjectTypes[index].ProjectType,
                  label:this.droplist.ProjectTypes[index].TypeName
                }
                this.form.projTypeOptions.push(temp)
              }
              for (var index in this.droplist.Oms) {
                var temp = {
                  value:this.droplist.Oms[index].ID,
                  label:this.droplist.Oms[index].RealName
                }
                this.form.contactMOptions.push(temp)
              }
              for (var index in this.droplist.Pms) {
                var temp = {
                  value:this.droplist.Pms[index].ID,
                  label:this.droplist.Pms[index].RealName
                }
                this.form.responseMOptions.push(temp)
              }
              resolve(response.data.Success)
            } else {
              this.$message.error(response.data.Msg)
              reject(response)
            }
          }).catch(function (response) {
            this.$message.error(response.data)
            reject(response)
          })
        })
      },
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(function(row) {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleCurrentChange(val){
        this.currentPage = val;
        this.getProjects(this.currentPage,true)
      },
      detailCheck(row){
        if(row.ID) {
          this.$router.push({
            path: '/panel/project/detail',
            query: {
              id: row.ID
            }
          })
        } else {
          this.$router.push({
            path: '/panel/project/detail'
          })
        }
      }
    }
  }
</script>
<style>
  .el-table th {
    text-align: center;
  }

  .el-table tbody tr td:first-child {
    text-align: center;
  }
  .manage-title h4{
    float: left;
    line-height: 36px;
  }
</style>
